﻿using System.Reflection;
using Autofac;
using EasyI18n.Api.Engines.Bases;
using EasyI18n.Api.Infrastructure.DataPersistence.EfCore;
using EasyI18n.Api.Infrastructure.DataPersistence.MongoDb;
using EasyI18n.Api.Infrastructure.DataPersistence.MongoDb.Entities.Bases;
using EasyI18n.Api.Infrastructure.MongoDb;
using MongoDB.Driver;

namespace EasyI18n.Api.Engines.MongoDbEngines;

public class RegisterMongoDb : IBuilderEngine
{
    private readonly ContainerBuilder containerBuilder;

    public RegisterMongoDb(ContainerBuilder containerBuilder)
    {
        this.containerBuilder = containerBuilder;
    }

    public void Run()
    {
        containerBuilder
            .RegisterType<MongoDbContext>()
            .AsSelf()
            .SingleInstance();
        var mongoEntityBaseType = typeof(IMongoDbEntity);
        var mongoEntityTypes = typeof(IMongoDbEntity).Assembly
            .ExportedTypes
            .Where(x => x is { IsClass: true, IsAbstract: false } && mongoEntityBaseType.IsAssignableFrom(x))
            .ToArray();
        var iDocType = typeof(IDocumentAccessor<>);
        var docType = typeof(DocumentAccessor<>);
        foreach (var mongoEntityType in mongoEntityTypes)
        {
            containerBuilder
                .RegisterType(docType.MakeGenericType(mongoEntityType))
                .AsSelf()
                .As(iDocType.MakeGenericType(mongoEntityType))
                .InstancePerLifetimeScope();
        }
    }
}